Right Shift Operator (`>>`)
The right shift operator (>>
) shifts the bits of its left-hand operand to the right by the number of positions specified by its right-hand operand. Each right shift operation essentially divides the number by 2
raised to the power of the number of positions shifted.
Example with var a int = 8
:
- Binary representation of
8
:00001000
8 >> 1
: shifts the bits one position to the right, resulting in00000100
, which is4
in decimal.8 >> 2
: shifts the bits two positions to the right, resulting in00000010
, which is2
in decimal.8 >> 3
: shifts the bits three positions to the right, resulting in00000001
, which is1
in decimal.
For signed integers:
- Binary representation of
-8
:11111000
(assuming two's complement) -8 >> 1
: shifts the bits one position to the right, resulting in11111100
, which is-4
in decimal.-8 >> 2
: shifts the bits two positions to the right, resulting in11111110
, which is-2
in decimal.-8 >> 3
: shifts the bits three positions to the right, resulting in11111111
, which is-1
in decimal.
For signed integers, the behavior depends on the language implementation, but in Go, the arithmetic right shift is used, where the sign bit is copied to maintain the number's sign.
Pattern explanation:
- Each shift to the right discards the least significant bit (rightmost position) and copies the sign bit (leftmost position) for signed integers, effectively dividing the number by
2
.
package main
import "fmt"
func main() {
var a int = 8
fmt.Println(a >> 1) // 4
fmt.Println(a >> 2) // 2
fmt.Println(a >> 3) // 1
var b int = -8
fmt.Println(b >> 1) // -4
fmt.Println(b >> 2) // -2
fmt.Println(b >> 3) // -1
}
Output:
4
2
1
-4
-2
-1